﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;


using Nancy.Json;
using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.Mvc.Formatters.Xml;
using SharpCifs.Smb;
using Models.Common;
using System.Drawing;
using System.Drawing.Imaging;
using Models.JsonResultModel;
using UtilsBase;
using UtilsCache;
using GatewayServer.Common;

namespace GatewayServer.Controllers
{
    public class CommonController : Controller
    {

        public string test()
        {
            var file = new SmbFile("smb://webfile:wGbF5W9f@192.168.197.217/UploadFile/aa.txt");
            //创建文件
            file.CreateNewFile();
            return "test";
        }

        public string test2()
        {
            var file = new SmbFile("smb://webfile:wGbF5W9f@127.0.0.1/UploadFile/fload/");
            //创建文件
            file.CreateNewFile();
            return "test";
        }
        public string test3()
        {
            var file = new SmbFile("smb://webfile:wGbF5W9f@127.0.0.1/UploadFile/floadaaa");
            file.Connect();
            //创建文件
            // file.Mkdir();
            bool aa = file.Exists();
            return "test";
        }
        public string addFileToServer(string base64stringdata, string oldfilename, string path = "", string newfilename = "", string time = "", string token = "")
        {
            #region

            var folder = new SmbFile("smb://" + UtilAppsettingCache.getSetting("MyWebSite:uploadPath"));



            //string dir = "";
            try
            {

                var pathfolder = new SmbFile("smb://" + UtilAppsettingCache.getSetting("MyWebSite:uploadPath"));
                pathfolder.Connect();
                if (!pathfolder.Exists())
                {
                    new SmbFile("smb://" + UtilAppsettingCache.getSetting("MyWebSite:uploadPath")).Mkdir();
                }

                pathfolder = new SmbFile("smb://" + UtilAppsettingCache.getSetting("MyWebSite:uploadPath") + path);
                pathfolder.Connect();
                //开始上传
                if (!pathfolder.Exists())
                {
                    new SmbFile("smb://" + UtilAppsettingCache.getSetting("MyWebSite:uploadPath") + path).Mkdir();
                    new SmbFile("smb://" + UtilAppsettingCache.getSetting("MyWebSite:uploadPath") + path + "/original").Mkdir();
                    new SmbFile("smb://" + UtilAppsettingCache.getSetting("MyWebSite:uploadPath") + path + "/big").Mkdir();
                    new SmbFile("smb://" + UtilAppsettingCache.getSetting("MyWebSite:uploadPath") + path + "/small").Mkdir();
                }
                else if (!new SmbFile("smb://" + UtilAppsettingCache.getSetting("MyWebSite:uploadPath") + path + "/original/").Exists())
                {
                    new SmbFile("smb://" + UtilAppsettingCache.getSetting("MyWebSite:uploadPath") + path + "/original").Mkdir();
                }

                string strext = oldfilename.Remove(0, oldfilename.LastIndexOf('.')).ToLower();

                if (newfilename == "")
                {
                    newfilename = Guid.NewGuid().ToString() + strext;
                }
                //图片上传到临时目录，
                string imgstr = base64stringdata;// Request.Query["base64stringdata"].ToString();
                byte[] imgBytes;

                if (imgstr.Contains(","))
                {
                    imgBytes = Convert.FromBase64String(imgstr.Remove(0, imgstr.IndexOf(',') + 1));
                }
                else
                {
                    imgBytes = Convert.FromBase64String(imgstr);
                }



                if (strext == ".jpg" || strext == ".gif" || strext == ".jpeg" || strext == ".bmp" || strext == ".png")
                {


                    Bitmap bitmap = GetImageFromBase64(imgBytes);
                    //图片压缩
                    string fdcPic = UpFileHelper.UFile_Mobile(bitmap, path, newfilename);
                    if (fdcPic == "")
                    {
                        //smfile.c.Delete();
                        // System.IO.File.Delete(file);
                        return "{\"respCode\":\"" + ResponseCode.System_ERROR + "\",\"respMsg\":\"" + ResponseCode.System_ERROR_MSG + "\",\"imgurl\":\"\"}";
                    }

                }
                else
                {

                    return "{\"respCode\":\"" + ResponseCode.System_ERROR + "\",\"respMsg\":\"" + ResponseCode.System_ERROR_MSG + "\",\"imgurl\":\"\"}";
                }

            }
            catch (Exception ex)
            {


                return "{\"respCode\":\"" + ResponseCode.System_ERROR + "\",\"respMsg\":\"" + ResponseCode.System_ERROR_MSG + ex.Message + "\",\"imgurl\":\"\"}";

            }

            #endregion
            return "{\"respCode\":\"" + ResponseCode.SUCCESS + "\",\"respMsg\":\"" + ResponseCode.SUCCESS_MSG + "\",\"imgurl\":\"" + newfilename + "\"}";

        }
        public Bitmap GetImageFromBase64(byte[] imgBytes)
        {



            MemoryStream ms = new MemoryStream(imgBytes);
            Bitmap bitmap = new Bitmap(ms);
            return bitmap;
        }

        public RespResultData addFileToServerforBase64(string base64stringdata, string oldfilename)
        {
            string returnFileName = UpFileHelper.UploadFile(base64stringdata, oldfilename);
            return RespResult.Sucess(returnFileName);
        }


        public string ChangeFile(string dir, string imgUrl, string path = "")
        {
            //图片改变方向 
            #region
            string fileName = imgUrl;
            //string mainDir = UtilAppsettingCache.getSetting("MyWebSite:uploadPath") + dir;// Server.MapPath(dir);

            //小图
            string newFileName = Guid.NewGuid().ToString().ToLower() + fileName.Substring(fileName.IndexOf("."), fileName.Length - fileName.IndexOf("."));

            var smfile = new SmbFile("smb://" + UtilAppsettingCache.getSetting("MyWebSite:uploadPath") + path + "/small/" + fileName);
            Image image = Image.FromStream(smfile.GetInputStream());
            Image image2 = KiRotate(image, "left");
            Bitmap map = new Bitmap(image2);
            byte[] imgBytes;
            string imgstr = ImgToBase64String(map);//转base64
            if (imgstr.Contains(","))
            {
                imgBytes = Convert.FromBase64String(imgstr.Remove(0, imgstr.IndexOf(',') + 1));
            }
            else
            {
                imgBytes = Convert.FromBase64String(imgstr);
            }
            var changebigsmfile = new SmbFile("smb://" + UtilAppsettingCache.getSetting("MyWebSite:uploadPath") + path + "/small/" + newFileName);
            changebigsmfile.CreateNewFile();
            var writeStream = changebigsmfile.GetOutputStream();
            //写入 bytes内容.
            writeStream.Write(imgBytes);
            //Dispose 可写的 stream.
            writeStream.Dispose();

            //image2.Save(newImageUrlBig);
            //System.IO.File.Delete(ImageUrlBig);
            map.Dispose();
            image2.Dispose();
            image.Dispose();

            //大图
            smfile = new SmbFile("smb://" + UtilAppsettingCache.getSetting("MyWebSite:uploadPath") + path + "/big/" + fileName);
            image = Image.FromStream(smfile.GetInputStream());
            image2 = KiRotate(image, "left");
            map = new Bitmap(image2);
            imgstr = ImgToBase64String(map);//转base64
            if (imgstr.Contains(","))
            {
                imgBytes = Convert.FromBase64String(imgstr.Remove(0, imgstr.IndexOf(',') + 1));
            }
            else
            {
                imgBytes = Convert.FromBase64String(imgstr);
            }
            changebigsmfile = new SmbFile("smb://" + UtilAppsettingCache.getSetting("MyWebSite:uploadPath") + path + "/big/" + newFileName);
            changebigsmfile.CreateNewFile();
            writeStream = changebigsmfile.GetOutputStream();
            //写入 bytes内容.
            writeStream.Write(imgBytes);
            //Dispose 可写的 stream.
            writeStream.Dispose();

            //image2.Save(newImageUrlBig);
            //System.IO.File.Delete(ImageUrlBig);
            map.Dispose();
            image2.Dispose();
            image.Dispose();




            // bigsmfile.Connect();
            // bigsmfile.Delete();
            string result = "{\"respCode\":\"" + ResponseCode.SUCCESS + "\",\"respMsg\":\"" + ResponseCode.SUCCESS_MSG + "\",\"imgurl\":\"" + newFileName + "\"}";
            return result;

            #endregion
        }
        public string ChangeFilebak(string dir, string imgUrl, string path = "")
        {
            //图片改变方向 
            #region
            string fileName = imgUrl;
            string ImageUrlBig, ImageUrlSmall = "";
            string mainDir = UtilAppsettingCache.getSetting("MyWebSite:uploadPath") + dir;// Server.MapPath(dir);
            ImageUrlBig = mainDir + path + "/big/" + fileName;
            ImageUrlSmall = mainDir + path + "/small/" + fileName;
            string newFileName = Guid.NewGuid().ToString().ToLower() + fileName.Substring(fileName.IndexOf("."), fileName.Length - fileName.IndexOf("."));

            Image image = Image.FromFile(ImageUrlBig);
            Image image2 = KiRotate(image, "left");
            string newImageUrlBig = mainDir + path + "/big/" + newFileName;
            image2.Save(newImageUrlBig);
            //System.IO.File.Delete(ImageUrlBig);
            image2.Dispose();
            image.Dispose();

            image = Image.FromFile(ImageUrlSmall);
            image2 = KiRotate(image, "left");
            string newImageUrlSmall = mainDir + path + "/small/" + newFileName;
            image2.Save(newImageUrlSmall);
            //  System.IO.File.Delete(ImageUrlSmall);
            image2.Dispose();
            image.Dispose();

            #endregion
            string result = "{\"respCode\":\"" + ResponseCode.SUCCESS + "\",\"respMsg\":\"" + ResponseCode.SUCCESS_MSG + "\",\"imgurl\":\"" + newFileName + "\"}";
            return result;

        }
        public static string ImgToBase64String(Bitmap bmp)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static Image KiRotate(Image img, string type)
        {
            //            顺时针旋转90度 RotateFlipType.Rotate90FlipNone
            //逆时针旋转90度 RotateFlipType.Rotate270FlipNone
            //水平翻转 RotateFlipType.Rotate180FlipY
            //垂直翻转 RotateFlipType.Rotate180FlipX 
            // try
            //     {
            if (type == "left")
            {
                img.RotateFlip(RotateFlipType.Rotate90FlipNone);
            }
            else if (type == "right")
            {
                img.RotateFlip(RotateFlipType.Rotate270FlipNone);
            }
            return img;
        }

    }
}